//package com.allwees.bs.c.module.payment.service.impl;
//
//import com.paypal.api.payments.Amount;
//import com.paypal.api.payments.Payment;
//import com.paypal.api.payments.PaymentExecution;
//import com.paypal.api.payments.RedirectUrls;
//import com.paypal.base.rest.APIContext;
//import com.paypal.base.rest.PayPalRESTException;
//import com.allwees.bs.c.module.order.dto.OrderDTO;
//import com.allwees.bs.c.module.order.entity.OrderEntity;
//import com.allwees.bs.c.module.order.repository.OrderItemRepository;
//import com.allwees.bs.c.module.order.repository.OrderRepository;
//import com.allwees.bs.c.module.order.service.IOrderService;
//import com.allwees.bs.c.module.payment.dto.PaymentPaypalDTO;
//import com.allwees.bs.c.module.payment.entity.PaymentLogEntity;
//import com.allwees.bs.c.module.payment.req.PaymentCreditCardReq;
//import com.allwees.bs.c.module.payment.req.PaymentPayPalCheckoutReq;
//import com.allwees.bs.c.module.payment.req.PaymentPaypalCreditCardReq;
//import com.allwees.bs.c.module.payment.service.IPaymentLogService;
//import com.allwees.bs.c.module.payment.service.IPaymentService;
//import com.allwees.bs.core.model.order.wf.order.EOrderState;
//import com.allwees.core.common.constant.EPlatform;
//import com.allwees.bs.core.modelbase.constant.ResultEnum;
//import com.allwees.bs.core.modelbase.exception.BusinessException;
//import com.allwees.support.payment.EPayMethod;
//import com.allwees.support.payment.model.PaymentInfo;
//import com.allwees.support.payment.paypal.PaypalAccountStrategy;
//import com.allwees.support.payment.paypal.configuration.PaypalProperties;
//import com.allwees.support.payment.paypal.util.PayPalUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.math.BigDecimal;
//
//@Slf4j
//@Service
//public class PaymentServiceImpl_bak implements IPaymentService {
//    @Autowired
//    private OrderRepository orderRepository;
//    @Autowired
//    private OrderItemRepository orderItemRepository;
//    @Autowired
//    private PaypalProperties paypalProperties;
//    @Autowired
//    private IPaymentLogService paymentLogService;
//    @Autowired
//    private IOrderService orderService;
//
//    @Override
//    @Transactional
//    public PaymentPaypalDTO createPaypalWeb(PaymentPayPalCheckoutReq req) {
//        OrderEntity order = canPayOrder(req.getOrderUuid());
//
//        PaymentInfo paymentInfo = new PaymentInfo()
//                .setPlatform(req.getPlatform())
//                .setPaypal(paypalProperties)
//                .setOrder(order)
//                .setOrderItems(orderItemRepository.findOrderItems(order.getUuid()));
//
//        Payment payment = PaypalAccountStrategy.create(paymentInfo);
//
//        PaymentLogEntity paymentLog = paymentLogService.savePaymentLog(payment.getId(), IPaymentLogService.PAYMENT_STATE_APPROVED, EPayMethod.PAYPAL, order);
//
//        return PaymentPaypalDTO.builder()
//                .approvalURL(PayPalUtil.getApprovalUrl(payment.getLinks().iterator()))
//                .expiredAt(paymentLog.getPaymentExpiresAt())
//                .payToken(paymentLog.getPaymentToken())
//                .paymentUuid(paymentLog.getUuid())
//                .build();
//    }
//
//    @Override
//    @Transactional
//    public OrderDTO payForCreditCard(PaymentPaypalCreditCardReq req, PaymentCreditCardReq creditCardReq) {
//        OrderEntity order = canPayOrder(req.getOrderUuid());
//
//        PaymentInfo paymentInfo = new PaymentInfo()
//                .setPlatform(req.getPlatform())
//                .setPaypal(paypalProperties)
//                .setOrder(order)
//                .setOrderItems(orderItemRepository.findOrderItems(order.getUuid()));
//
//        Payment payment = PaypalCreditCardStrategy.create(paymentInfo);
//
//        PaymentLogEntity paymentLog = paymentLogService.savePaymentLog(payment.getId(), IPaymentLogService.PAYMENT_STATE_CREATED, EPayMethod.CREDIT_CARD, order);
//
//        return orderService.payOrder(req.getOrderUuid(), paymentLog.getUuid(), PayPalUtil.analysisPaymentType(payment));
//    }
//
//    @Override
//    @Transactional
//    public OrderDTO paypalCallBack(String paymentId, String payId) {
//
//        APIContext apiContext = new APIContext(paypalProperties.getClientId(), paypalProperties.getSecret(), paypalProperties.getMode());
//
//        // 生成paypal支付对象
//        Payment payment = new Payment().setId(paymentId);
//
//        try {
//            payment = payment.execute(apiContext, new PaymentExecution().setPayerId(payId));
//        } catch (Exception e) {
//            log.error(">>>>>>>>>> paypal execute error,paymentId:{},payId:{}", paymentId, payId, e);
//            throw BusinessException.getInstance(ResultEnum.PAYMENT_PAYPAL_CREATE_ERROR);
//        }
//        if (!PayPalUtil.isSuccess(payment.getState())) {
//            log.error(">>>>>>>> paypal回调支付不是approved" + payment.getState() + "paymentId：" + paymentId);
//            return null;
//        }
//
//        PaymentLogEntity paymentLog = paymentLogService.updatePayedPaymentLog(paymentId, payId, payment);
//
//        // 支付成功，通知订单修改状态
//        return this.orderService.payOrder(paymentLog.getOrderUuid(), paymentLog.getUuid(), PayPalUtil.analysisPaymentType(payment));
//    }
//
//    /**
//     * paypal 回调机制
//     */
//    @Override
//    public void paypalWebHooks(String paymentId) {
//        APIContext apiContext = new APIContext(paypalProperties.getClientId(), paypalProperties.getSecret(), paypalProperties.getMode());
//        Payment payment = null;
//        try {
//            payment = Payment.get(apiContext, paymentId);
//        } catch (PayPalRESTException e) {
//            log.error(">>>>>>>>>>paypal webhook get error,payment token :{}", paymentId);
//            return;
//        }
//        String orderUuid = payment.getTransactions().get(0).getCustom();
//        if (StringUtils.isBlank(orderUuid)) {
//            log.error(">>>>>>>>>>paypal webhook中未获取到订单uuid,payment token :{}", paymentId);
//            return;
//        }
//
//        OrderEntity order = checkWebHook(payment, orderUuid);
//        if (order.getPayed()) {
//            return;
//        }
//        PaymentLogEntity paymentLog = paymentLogService.savePaymentLog(paymentId, IPaymentLogService.PAYMENT_STATE_APPROVED, EPayMethod.valueOf(payment.getPayer().getPaymentMethod().toUpperCase()), order);
//
//        // 支付成功，通知订单修改状态，只是通知订单已支付完成，不直接修改订单状态等
//        this.orderService.payOrder(paymentLog.getOrderUuid(), paymentLog.getUuid(), PayPalUtil.analysisPaymentType(payment));
//    }
//
//    private OrderEntity checkWebHook(Payment payment, String orderUuid) {
//        OrderEntity order = this.orderRepository.getByUuid(orderUuid);
//        if (order == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//
//        // 检查付的金额是否和订单金额相同
//        Amount amount = payment.getTransactions().get(0).getAmount();
//        if (!order.getAmt().equals(new BigDecimal(amount.getTotal()))) {
//            throw BusinessException.getInstance(ResultEnum.CONSISTENCY_ERROR);
//        }
//        // 检查货币是否和订单货币相同
//        if (!order.getCurrency().equals(amount.getCurrency())) {
//            throw BusinessException.getInstance(ResultEnum.CONSISTENCY_ERROR);
//        }
//        return order;
//    }
//
//    /**
//     * paypal 创建
//     *
//     * @param payment
//     * @param order
//     * @return
//     */
//    private Payment paypalCreate(Payment payment, OrderEntity order) {
//
//        APIContext apiContext = new APIContext(paypalProperties.getClientId(), paypalProperties.getSecret(), paypalProperties.getMode());
//
//        try {
//            payment = payment.create(apiContext);
//        } catch (Exception e) {
//            log.error(">>>>>>>>>> paypal create error,order uuid:{}", order.getUuid(), e);
//            throw BusinessException.getInstance(ResultEnum.PAYMENT_PAYPAL_CREATE_ERROR);
//        }
//        return payment;
//    }
//
//    private OrderEntity canPayOrder(String orderUuid) {
//
//        // 获取订单，并根据订单的情况和信息进行处理
//        OrderEntity order = this.orderRepository.getByUuid(orderUuid);
//        if (order == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//
//        // 只有待支付的情况下才能进行支付
//        if (!EOrderState.CREATED.equals(order.getState())) {
//            throw BusinessException.getInstance(ResultEnum.PAYMENT_ORDER_STATE_IS_NOT_UNPAID);
//        }
//        return order;
//    }
//
//    private RedirectUrls buildRedirectUrls(String orderUuid, EPlatform platform) {
//
//        RedirectUrls redirectUrls = new RedirectUrls();
//        redirectUrls.setCancelUrl(paypalProperties.getCancelURL() + "?orderUuid=" + orderUuid + "&platform=" + platform.name());
//        redirectUrls.setReturnUrl(paypalProperties.getReturnURL() + "?orderUuid=" + orderUuid + "&platform=" + platform.name());
//
//        return redirectUrls;
//    }
//}
